package com.example.config.sentinel;



import com.alibaba.csp.sentinel.adapter.gateway.common.command.UpdateGatewayRuleCommandHandler;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.datasource.FileWritableDataSource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * @Description: 限流规则持久化
 * @author: bright
 * @Date: 2020/9/25 13:46
 */
@Configuration
@Order(0)
public class SentinelPersistenceConfig {

    @PostConstruct
    public void dynamicGatewayFlowRule() throws Exception {
        //没有则建立
        String flowRulePath = "E:/gateway-flow-rule.json";
        ReadableDataSource<String, Set<GatewayFlowRule>> ds = new FileRefreshableDataSource<>(
                flowRulePath, source -> JSON.parseObject(source, new TypeReference<Set<GatewayFlowRule>>() {
        })
        );
        // 将可读数据源注册至 GatewayRuleManager(gateway相关规则)
        // 这样当规则文件发生变化时，就会更新规则到内存
        GatewayRuleManager.register2Property(ds.getProperty());
        // 收到控制台推送的规则时，Sentinel 会先更新到内存，然后将规则写入到文件中.
        WritableDataSource<Set<GatewayFlowRule>> wds = new FileWritableDataSource<>(flowRulePath, (t) -> JSON.toJSONString(t));
        UpdateGatewayRuleCommandHandler.setWritableDataSource(wds);
    }

}
